﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Creative85.Framework.Data;
using Project32CHE.Biz.Goods.Model;
using NPoco;
using Creative85.Framework.Utilities;
using System.Runtime.Caching;

namespace Project32CHE.Biz.Goods
{
    public static class GoodsCategoryService
    {
        #region 缓存操作变量和方法
        private static ObjectCache container = new CacheUtility(typeof(GoodsCategoryService).FullName);

        private static readonly string CacheName_SplitChar = "|";
        private static readonly string CacheName_GoodsModel = "Goods";

        private static string generateCacheKey(object ext, params string[] types)
        {
            if (types == null) { types = new string[0]; }
            Array.Sort(types);
            StringBuilder sb = new StringBuilder(string.Join(CacheName_SplitChar, types));
            sb.Insert(0, CacheName_SplitChar);
            sb.Append(CacheName_SplitChar);
            sb.Append(ext);
            return sb.ToString();
        }
        private static T getORsetCacheItem<T>(Func<T> addFunction, object ext, params string[] types) where T : class
        {
            var cacheName = generateCacheKey(ext, types);
            var cacheValue = container.Get(cacheName, null) as T;
            if (cacheValue == null)
            {
                cacheValue = addFunction();
                container.Set(cacheName, cacheValue, new CacheItemPolicy() { SlidingExpiration = new TimeSpan(24, 0, 0) }, null);
            }
            //cacheValue = ModelUtility.Copy(cacheValue);
            return cacheValue;
        }
        private static void removeCacheItem(object ext, params string[] types)
        {
            var cacheName = generateCacheKey(ext, types);
            container.Remove(cacheName, null);
        }
        #endregion


        public static List<string> GetCategoryNamePath(Guid ID)
        {
            var model = Get(ID);
            if (!model.ParentID.Equals(Guid.Empty))
            {
                var list = GetCategoryNamePath(model.ParentID);
                list.Add(model.Name);
                return list;
            }
            return new List<string>();//默认全部没有分类名称
        }

        private static int getCode(Guid parentId, Guid shopId, bool isReuse = false)
        {
            var subList = GetSub(parentId);
            var code = 0;
            var shopList = subList.Where(x => x.ShopID.HasValue && x.ShopID.Value == shopId).ToList();
            if (shopList.Count == 0) { code = 100; }
            else
            {
                var c = 0;
                var l = shopList
                    .Select(x => x.Code)
                    .Select(x => x.Substring(x.Length - 3))
                    .Select(x => int.Parse(x))
                    .OrderBy(x => x)
                    .ToList();
                if (isReuse)
                {
                    var index = l.First();
                    var indexs = l
                        .Select(x => new
                        {
                            index = index++,
                            code = x
                        })
                        .Where(x => x.index != x.code)
                        .Select(x => x.index)
                        .OrderBy(x => x)
                        .ToList();
                    if (indexs.Count == 0) { c = index; }
                    else { c = indexs.First() - 1; }
                }
                else
                {
                    c = l
                        .OrderByDescending(x => x)
                        .First();
                }
                code = c;
            }
            return (code + 1);
        }
        private static List<GoodsCategory> getSubShareGoodsCategory(Guid parentId)
        {
            var list = Db.Instance.Query<GoodsCategory>()
                .Where(x => x.IsDeleted == false)
                .Where(x => x.ParentID == parentId)
                .Where(x => x.UnionID == null && x.ShopID == null)
                .OrderBy(x => x.OrderID)
                .ToList();
            return list;
        }
        private static List<GoodsCategory> getSubUnionGoodsCategory(Guid parentId, Guid unionId)
        {
            var list = Db.Instance.Query<GoodsCategory>()
                .Where(x => x.IsDeleted == false)
                .Where(x => x.ParentID == parentId)
                .Where(x => x.UnionID == unionId && x.ShopID == null)
                .OrderBy(x => x.OrderID)
                .ToList();
            return list;
        }
        private static List<GoodsCategory> getSubShopGoodsCategory(Guid parentId, Guid shopId)
        {
            var list = Db.Instance.Query<GoodsCategory>()
                .Where(x => x.IsDeleted == false)
                .Where(x => x.ParentID == parentId)
                .Where(x => x.ShopID == shopId)
                .OrderBy(x => x.OrderID)
                .ToList();
            return list;
        }

        public static List<GoodsCategory> Get(Guid unionId, Guid? shopId)
        {
            var list = new List<GoodsCategory>();
            if (shopId.HasValue)
            {
                var q = Db.Instance.Query<GoodsCategory>()
                    .Where(x => x.IsDeleted == false)
                    .Where(x => (x.UnionID == null && x.ShopID == null) || (x.UnionID == unionId && x.ShopID == null) || (x.ShopID == shopId.Value))
                    .ToList();
                list.AddRange(q);
            }
            else
            {
                var q = Db.Instance.Query<GoodsCategory>()
                    .Where(x => x.IsDeleted == false)
                    .Where(x => (x.UnionID == null && x.ShopID == null) || (x.UnionID == unionId && x.ShopID == null))
                    .ToList();
                list.AddRange(q);
            }
            return list;
        }

        /// <summary>
        /// 获取指定Id的直接下级
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public static List<GoodsCategory> GetSub(Guid parentId)
        {
            var list = Db.Instance.Query<GoodsCategory>().Where(x => x.ParentID == parentId && x.IsDeleted == false).OrderBy(x => x.OrderID).ToList();
            return list;
        }
        /// <summary>
        /// 获取指定ID的分类
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static GoodsCategory Get(Guid id)
        {
            return getORsetCacheItem(
                () => Db.Instance.SingleById<GoodsCategory>(id),
                id,
                CacheName_GoodsModel);
        }
        /// <summary>
        /// 获取指定分类的直接下级分类
        /// </summary>
        /// <param name="parentId"></param>
        /// <param name="unionId"></param>
        /// <param name="shopId"></param>
        /// <returns></returns>
        public static List<GoodsCategory> GetSubGoodsCategory(Guid parentId, Guid unionId, Guid? shopId)
        {
            var list = new List<GoodsCategory>();
            list.AddRange(getSubShareGoodsCategory(parentId));
            list.AddRange(getSubUnionGoodsCategory(parentId, unionId));
            if (shopId.HasValue)
            {
                list.AddRange(getSubShopGoodsCategory(parentId, shopId.Value));
            }
            list = list.OrderBy(x => x.OrderID).ToList();
            return list;
        }
    }
}
